import { ChatContext } from '@/app/chat-context';
import { apiInterceptors, login as authLogin } from '@/client/api';
import { STORAGE_USERINFO_KEY, STORAGE_USERINFO_VALID_TIME_KEY } from '@/utils/constants/index';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, message } from 'antd';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useContext, useState } from 'react';
import { useTranslation } from 'react-i18next';

interface LoginFormValues {
  username: string;
  password: string;
  remember: boolean;
}

function Login() {
  const { t } = useTranslation();
  const router = useRouter();
  const { mode } = useContext(ChatContext);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const onFinish = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      // 调用真实的登录API
      const [error, data] = await apiInterceptors(
        authLogin({
          username: values.username,
          password: values.password,
        }),
      );

      if (error || !data) {
        message.error(t('login_failed') || '登录失败，请重试！');
        return;
      }
      
      console.log('Login response data:', data);
      console.log('User menus:', data.menus);
      console.log('User permissions:', data.permissions);

      // 保存Token到localStorage
      if (data.token?.access_token) {
        localStorage.setItem('auth_token', data.token.access_token);
        localStorage.setItem('token_expires_at', String(Date.now() + data.token.expires_in * 1000));
      }

      // 保存菜单和权限到localStorage
      if (data.menus) {
        localStorage.setItem('user_menus', JSON.stringify(data.menus));
        console.log('Saved user_menus to localStorage');
      } else {
        console.warn('No menus in login response!');
      }
      if (data.permissions) {
        localStorage.setItem('user_permissions', JSON.stringify(data.permissions));
      }

      // 保存用户信息到localStorage
      const userInfo = {
        user_channel: 'dbgpt',
        user_no: data.user.username,
        user_id: data.user.id,
        nick_name: data.user.nick_name || data.user.username,
        email: data.user.email,
        role: 'normal' as const,
      };

      localStorage.setItem(STORAGE_USERINFO_KEY, JSON.stringify(userInfo));
      localStorage.setItem(STORAGE_USERINFO_VALID_TIME_KEY, Date.now().toString());

      message.success(t('login_success') || '登录成功！');

      // 跳转到首页
      setTimeout(() => {
        router.push('/chat');
      }, 500);
    } catch (error) {
      console.error('Login error:', error);
      message.error(t('login_failed') || '登录失败，请重试！');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className='flex items-center justify-center min-h-screen w-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900'>
      {/* 背景装饰 */}
      <div className='absolute inset-0 overflow-hidden pointer-events-none'>
        <div className='absolute -top-40 -right-40 w-80 h-80 bg-blue-300 dark:bg-blue-900 rounded-full mix-blend-multiply dark:mix-blend-soft-light filter blur-xl opacity-30 animate-blob'></div>
        <div className='absolute -bottom-40 -left-40 w-80 h-80 bg-purple-300 dark:bg-purple-900 rounded-full mix-blend-multiply dark:mix-blend-soft-light filter blur-xl opacity-30 animate-blob animation-delay-2000'></div>
        <div className='absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 h-80 bg-pink-300 dark:bg-pink-900 rounded-full mix-blend-multiply dark:mix-blend-soft-light filter blur-xl opacity-30 animate-blob animation-delay-4000'></div>
      </div>

      {/* 登录卡片 */}
      <div className='relative z-10 w-full max-w-md px-6'>
        <div className='bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8 backdrop-blur-sm bg-opacity-95 dark:bg-opacity-95 border border-gray-100 dark:border-gray-700'>
          {/* Logo和标题 */}
          <div className='flex flex-col items-center mb-8'>
            <div className='mb-6 animate-fade-in'>
              <Image
                src={mode === 'dark' ? '/logo_s_latest.png' : '/logo_zh_latest.png'}
                alt='DB-GPT'
                width={180}
                height={60}
                priority
              />
            </div>
            <h1 className='text-2xl font-bold text-gray-800 dark:text-white mb-2 animate-fade-in animation-delay-200'>
              {t('welcome_back') || '欢迎回来'}
            </h1>
            <p className='text-gray-500 dark:text-gray-400 text-sm animate-fade-in animation-delay-400'>
              {t('login_subtitle') || '登录以继续使用 DB-GPT'}
            </p>
          </div>

          {/* 登录表单 */}
          <Form
            form={form}
            name='login'
            initialValues={{ remember: true }}
            onFinish={onFinish}
            size='large'
            className='animate-fade-in animation-delay-600'
          >
            <Form.Item
              name='username'
              rules={[
                { required: true, message: t('please_input_username') || '请输入用户名！' },
                { min: 3, message: t('username_min_length') || '用户名至少3个字符！' },
              ]}
            >
              <Input
                prefix={<UserOutlined className='text-gray-400' />}
                placeholder={t('username') || '用户名'}
                className='rounded-lg'
              />
            </Form.Item>

            <Form.Item
              name='password'
              rules={[
                { required: true, message: t('please_input_password') || '请输入密码！' },
                { min: 6, message: t('password_min_length') || '密码至少6个字符！' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined className='text-gray-400' />}
                placeholder={t('password') || '密码'}
                className='rounded-lg'
              />
            </Form.Item>

            <Form.Item>
              <div className='flex items-center justify-between'>
                <Form.Item name='remember' valuePropName='checked' noStyle>
                  <Checkbox className='text-gray-600 dark:text-gray-300'>{t('remember_me') || '记住我'}</Checkbox>
                </Form.Item>
                <a className='text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 text-sm'>
                  {t('forgot_password') || '忘记密码？'}
                </a>
              </div>
            </Form.Item>

            <Form.Item>
              <Button
                type='primary'
                htmlType='submit'
                loading={loading}
                block
                className='h-12 rounded-lg text-base font-medium bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 border-0 shadow-lg'
              >
                {loading ? t('logging_in') || '登录中...' : t('login') || '登录'}
              </Button>
            </Form.Item>
          </Form>

          {/* 分割线 */}
          {/* <div className='relative my-6'>
            <div className='absolute inset-0 flex items-center'>
              <div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
            </div>
            <div className='relative flex justify-center text-sm'>
              <span className='px-4 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400'>{t('or') || '或'}</span>
            </div>
          </div> */}

          {/* 第三方登录 */}
          <div className='space-y-3'>
            {/* <Button
              block
              className='h-12 rounded-lg border-gray-300 dark:border-gray-600 hover:border-blue-500 dark:hover:border-blue-400'
              onClick={() => message.info(t('feature_coming_soon') || '功能即将推出')}
            >
              <div className='flex items-center justify-center'>
                <svg className='w-5 h-5 mr-2' viewBox='0 0 24 24'>
                  <path
                    fill='currentColor'
                    d='M12.545,10.239v3.821h5.445c-0.712,2.315-2.647,3.972-5.445,3.972c-3.332,0-6.033-2.701-6.033-6.032s2.701-6.032,6.033-6.032c1.498,0,2.866,0.549,3.921,1.453l2.814-2.814C17.503,2.988,15.139,2,12.545,2C7.021,2,2.543,6.477,2.543,12s4.478,10,10.002,10c8.396,0,10.249-7.85,9.426-11.748L12.545,10.239z'
                  />
                </svg>
                {t('login_with_google') || '使用 Google 登录'}
              </div>
            </Button> */}

            {/* <Button
              block
              className='h-12 rounded-lg border-gray-300 dark:border-gray-600 hover:border-blue-500 dark:hover:border-blue-400'
              onClick={() => message.info(t('feature_coming_soon') || '功能即将推出')}
            >
              <div className='flex items-center justify-center'>
                <svg className='w-5 h-5 mr-2' viewBox='0 0 24 24'>
                  <path
                    fill='currentColor'
                    d='M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z'
                  />
                </svg>
                {t('login_with_github') || '使用 GitHub 登录'}
              </div>
            </Button> */}
          </div>

          {/* 注册提示 */}
          <div className='mt-6 text-center text-sm text-gray-600 dark:text-gray-400'>
            {t('no_account') || '还没有账号？'}{' '}
            <a className='text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 font-medium cursor-pointer'>
              {t('register') || '立即注册'}
            </a>
          </div>
        </div>

        {/* 页脚信息 */}
        <div className='mt-8 text-center text-sm text-gray-500 dark:text-gray-400'>
          <p>&copy; 2024 DB-GPT. {t('all_rights_reserved') || '保留所有权利'}</p>
        </div>
      </div>
    </div>
  );
}

export default Login;
